<template>
  <div ref="chartContainer" class="heatmap-container" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import * as echarts from "echarts";
import type { ECharts } from "echarts";

const props = defineProps({
  areas: {
    type: Array,
    required: true
  },
  currentView: {
    type: String,
    default: "temperature"
  },
  isRefreshing: {
    type: Boolean,
    default: false
  }
});

// const emit = defineEmits(["area-click"]);
const emit = defineEmits(["area-click", "rendered"]);

const chartContainer = ref<HTMLElement | null>(null);
let chart: ECharts | null = null;

// 初始化图表
onMounted(() => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value);
    updateChart();

    // 添加点击事件
    chart.on("click", (params: any) => {
      const area = props.areas.find((a: any) => Math.abs(a.x * 200 - params.data[0]) < 1 && Math.abs(a.y * 200 - params.data[1]) < 1);
      if (area) {
        emit("area-click", area);
      }
      // emit("area-click", area);
      console.log(area, params, "params");
    });
  }
});

// 更新图表
const updateChart = () => {
  if (!chart || props.isRefreshing) return;

  const { data, xData, yData } = generateHeatmapData();

  const option = {
    animation: false,
    silent: false,
    grid: {
      top: 10,
      right: 10,
      bottom: 10,
      left: 10,
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xData,
      show: false,
      splitLine: { show: false }
    },
    yAxis: {
      type: "category",
      data: yData,
      show: false,
      splitLine: { show: false }
    },
    visualMap: {
      type: "continuous",
      min: props.currentView === "temperature" ? 20 : 45, // 包含0值
      max: props.currentView === "temperature" ? 25 : 55,
      calculable: true,
      orient: "horizontal",
      left: "center",
      bottom: "5%",
      text: props.currentView === "temperature" ? ["高温", "低温"] : ["高湿", "低湿"],
      inRange: {
        color:
          props.currentView === "temperature"
            ? [
                "rgba(255,255,255,0)",
                "rgba(255,240,240,0.1)",
                "rgba(255,220,220,0.2)",
                "rgba(255,180,180,0.4)",
                "rgba(255,120,120,0.6)",
                "rgba(255,60,60,0.8)",
                "rgba(255,0,0,1)"
              ]
            : [
                "rgba(255,255,255,0)",
                "rgba(240,240,255,0.1)",
                "rgba(220,220,255,0.2)",
                "rgba(180,180,255,0.4)",
                "rgba(120,120,255,0.6)",
                "rgba(60,60,255,0.8)",
                "rgba(0,0,255,1)"
              ]
      }
    },
    series: [
      {
        name: props.currentView === "temperature" ? "温度" : "湿度",
        type: "heatmap",
        data: data,
        emphasis: {
          // disabled: true
          itemStyle: {
            borderColor: "rgba(0, 0, 0, 0)",
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        itemStyle: {
          borderWidth: 0,
          opacity: 0.9
          // 明确设置0值的颜色
          // color: props.currentView === "temperature" ? "rgba(1, 56, 106, 0.1)" : "rgba(26, 35, 126, 0.1)"
        },
        // progressive: 2000,
        // progressiveThreshold: 3000,
        progressive: false,
        // filterMode: "none", // 禁用自动过滤
        animation: false,
        label: {
          show: true,
          formatter: function (params: any) {
            const area: any = props.areas.find((a: any) => Math.abs(a.x * 200 - params.data[0]) < 1 && Math.abs(a.y * 200 - params.data[1]) < 1);
            if (area) {
              const value = props.currentView === "temperature" ? area.valueNewTemp + "°C" : area.valueNewHumidity + "%";
              return area.name + "\n" + value;
            }
            return "";
          },
          color: "#000",
          fontSize: 12,
          fontWeight: "bold",
          textShadowColor: "#fff",
          textShadowBlur: 3
        }
      }
    ]
  };

  chart.setOption(option, { notMerge: true });
  emit("rendered");
};

// 生成热力图数据
const generateHeatmapData = () => {
  const data: any[] = [];
  const xData: number[] = [];
  const yData: number[] = [];

  for (let i = 0; i <= 200; i++) {
    xData.push(i / 200);
    yData.push(i / 200);
  }

  props.areas.forEach((area: any) => {
    // 确保值为0时也能生成数据
    const value = Math.max(props.currentView === "temperature" ? area.valueNewTemp : area.valueNewHumidity, 0);
    const radius = 0.1;
    const step = 0.005;

    if (value === 0) {
      // 为0值生成最小数据点
      data.push([Math.round(area.x * 200), Math.round(area.y * 200), 0.001]);
    } else {
      // 正常生成热力数据
      for (let dx = -radius; dx <= radius; dx += step) {
        for (let dy = -radius; dy <= radius; dy += step) {
          const distance = Math.sqrt(dx * dx + dy * dy);
          if (distance <= radius) {
            const intensity = Math.exp(-distance * 2.5);
            const centerBoost = distance < 0.1 ? 1.2 : 1.0;
            data.push([Math.round((area.x + dx) * 200), Math.round((area.y + dy) * 200), value * intensity * centerBoost]);
          }
        }
      }
    }
  });

  return { data, xData, yData };
};

// 监听属性变化
watch(() => props.currentView, updateChart);
watch(() => props.areas, updateChart, { deep: true });

// 暴露方法给父组件
defineExpose({
  updateChart
});
</script>

<style scoped>
.heatmap-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  width: 100%;
  height: 100%;
}
</style>
